package com.mccken.demo.lock;

import org.openjdk.jol.info.ClassLayout;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Test1 {
    @SneakyThrows
    public static void main(String[] args) throws InterruptedException {
        //HotSpot 虚拟机在启动后有个 4s 的延迟才会对每个新建的对象开启偏向锁模式
        Thread.sleep(5000);
        Object obj = new Object();
        log.debug("匿名偏向状态 =====================" + "\n" + ClassLayout.parseInstance(obj).toPrintable());
        obj.hashCode();
        log.debug("hashCode 未锁之时 =====================" + "\n" + ClassLayout.parseInstance(obj).toPrintable());
        new Thread(() -> {
            synchronized (obj) {
                Thread thread = Thread.currentThread();
                obj.hashCode();
                log.debug("偏向锁线程id："+thread.getId());
                log.debug(thread.getName() + "获取锁执行中。。。\n"
                        + ClassLayout.parseInstance(obj).toPrintable());
            }
        }, "thread-a").start();

    }
}
